package com.rfid.a252robot.activity.presenter;

import android.graphics.Bitmap;
import android.os.Handler;
import android.text.TextUtils;

import com.king.zxing.util.CodeUtils;
import com.rfid.a252robot.activity.view.IBookListView;
import com.rfid.a252robot.base.BasePresenter;
import com.rfid.a252robot.bean.Box;
import com.rfid.a252robot.bean.Row;
import com.rfid.a252robot.net.BoxLibApi;
import com.rfid.db.bean.Book;
import com.rfid.manager.DBManager;
import com.spectre.generate.ConfigManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class BookListPresenter extends BasePresenter<IBookListView> {

    Executor mExecutor = Executors.newSingleThreadExecutor();
    Handler mHandler = new Handler();

    public List<Book> getBooks() {
        return DBManager.getCanBorrowBooks();
    }

    public void queryBookByCode(String code) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String barcode = BoxLibApi.INSTANCE.getBookByCode(code);
                    Book book = DBManager.getBook(barcode);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mView != null) {
                                mView.onBook(book);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void getQrBitmap() {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String qrUrl = ConfigManager.INSTANCE.getGlobalConfig().getQrUrl();
                if (!TextUtils.isEmpty(qrUrl)) {
                    String url = qrUrl + "?cabinet=" + ConfigManager.INSTANCE.getGlobalConfig().getCabinet();
                    Bitmap bm = CodeUtils.createQRCode(url, 200);
                   mHandler.post(new Runnable() {
                       @Override
                       public void run() {
                           mView.onQrBitmap(bm);
                       }
                   });
                }
            }
        });
    }

}
